package org.hepeng.workx.util.serializer;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * @author he peng
 */
public class JdkObjectSerializer<T> extends ExceptionTranslationObjectSerializer<T> {

    @Override
    protected byte[] convert(T object) throws Exception {
        ObjectSerializationUtils.serializableCheck(object);
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream(1024);
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteStream);
        objectOutputStream.writeObject(object);
        objectOutputStream.flush();
        return byteStream.toByteArray();
    }

    @Override
    protected T convert(byte[] bytes) throws Exception {
        ByteArrayInputStream byteStream = new ByteArrayInputStream(bytes);
        ObjectInputStream objectInputStream = new ObjectInputStream(byteStream);
        return (T) objectInputStream.readObject();
    }
}
